﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PerfAnalyzerUI
{
	/// <summary>
	/// Abstract class to help managing a DataGridView
	/// </summary>
	abstract class DataGridViewHelper
	{
		/// <summary>
		/// DataGridView to help manage.
		/// </summary>
		protected DataGridView _dataGridView;

		protected Form _parentForm;

		/// <summary>
		/// Names of the columns.
		/// </summary>
		List<string> ColumnNames = new List<string>();

		protected Dictionary<Object, DataGridViewRow> TagToRow = new Dictionary<Object, DataGridViewRow>();

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="trackedDataGridView">DataGridView to help manage.</param>
		public DataGridViewHelper(DataGridView trackedDataGridView, Form parentForm)
		{
			if (null == trackedDataGridView)
			{
				throw new ArgumentNullException("trackedDataGridView", "Cannot have a null DataGridView to manage.");
			}

			if (null == parentForm)
			{
				throw new ArgumentNullException("container", "Cannot have a null parent Form to manage.");
			}

			_dataGridView = trackedDataGridView;
			_parentForm = parentForm;
		}

		/// <summary>
		/// Set the columns names of the DataGridView.
		/// </summary>
		/// <param name="columns">List of columns.</param>
		public void SetColumns(List<string> columns)
		{
			if (null == columns || 0 == columns.Count)
			{
				throw new ArgumentException("Columns cannot be null or empty.");
			}

			ColumnNames.AddRange(columns);
		}

		public DataGridViewRow GetRow(object tag)
        {
			return TagToRow[tag];
        }

		public List<Object> GetSelectedTags()
		{
			List<Object> selectedtags = new List<object>();

			foreach (DataGridViewRow row in _dataGridView.SelectedRows)
			{
				selectedtags.Add(row.Tag);
			}

			return selectedtags;
		}

		abstract public DataGridViewRow AddRow(Object tag);
		abstract public void AddRows(IEnumerable<Object> tags);

		abstract public void RemoveRow(DataGridViewRow tag);

		abstract public void Clear();

		/// <summary>
		/// Remove selected rows.
		/// </summary>
		public void RemoveSelection()
		{
			DataGridViewSelectedRowCollection selected = _dataGridView.SelectedRows;

			foreach (DataGridViewRow row in selected)
			{
				RemoveRow(row);
			}
		}

		/// <summary>
		/// Unselect selected rows.
		/// </summary>
		public void ClearSelection()
		{
			_dataGridView.ClearSelection();
		}

		/// <summary>
		/// Select and focus the row containing the given tag.
		/// </summary>
		/// <param name="row"></param>
		public void SelectAndFocus(object tag)
		{
			var row = TagToRow[tag];
			row.Selected = true;
			_dataGridView.CurrentCell = row.Cells[0];
		}
	}
}
